/**
 * 
 */
package com.brother.goallife;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate4.HibernateTemplate;

/**
 * @author anhtuan_truong Using Hibernate 4
 */
public class HibernateDaoTemplate<T> extends HibernateTemplate {

	private Class classType;

	public HibernateDaoTemplate(Class classType) {
		this.classType = classType;
	}

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(DetachedCriteria criteria) {
		return (List<T>) super.findByCriteria(criteria);
	}

	public T findById(int id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(classType);
		criteria.add(Restrictions.eq("id", id));
		List<T> findByCriteria = findByCriteria(criteria);
		if (findByCriteria.isEmpty()) {
			return null;
		}
		return findByCriteria.get(0);
	}

	public void delete(Object entity) {
		super.delete(entity);
	}

	public T findFirstByCriteria(DetachedCriteria criteria) {
		@SuppressWarnings("unchecked")
		List<T> tempResult = (List<T>) super.findByCriteria(criteria);
		if (tempResult.isEmpty()) {
			return null;
		}
		return tempResult.get(0);
	}

}
